package org.jjj.prod.service.impl;

import org.jjj.prod.domain.ProductType;
import org.jjj.prod.mapper.ProductTypeMapper;
import org.jjj.prod.service.IProductTypeService;
import org.jjj.org.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiangjianjun
 * @since 2022-10-22
 */
@Service
public class ProductTypeServiceImpl extends BaseServiceImpl<ProductType> implements IProductTypeService {
    @Autowired
    private ProductTypeMapper productTypeMapper;
    /**
     * 新增和修改需要在后端拼接path字段
     */
    @Override
    public void add(ProductType productType) {
        //第一步：先新增到数据库然后返回类型自增的id值
        super.add(productType);
        //path:父类型的path+/自己的id
        //第二步：判断一下父类型是否有值，如果没值说明自己就是一级类型
        String path ="";
        Long id = productType.getId();
        if (productType.getChildren()==null){
            path="/"+id;
        }
        //第三步：先拿到父类型的id
        Long pid = productType.getParent().getId();
        //根据父类型id去数据库查出父类型,然后取到父类型的path
        ProductType parent = productTypeMapper.selectById(pid);
        path = parent.getPath()+"/"+id;
        //得到path之后重新给path赋值然后更新数据库就存进去了
        productType.setPath(path);
        super.update(productType);
    }

    @Override
    public void update(ProductType productType) {
        Long id = productType.getId();
        String path = "";
        if (productType.getParent()==null){
            path = "/"+id;
        }
        ProductType parent = productTypeMapper.selectById(productType.getParent().getId());
        path = parent.getPath()+"/"+id;
        productType.setPath(path);
        super.update(productType);
    }

    /**
     * 获取类型树
     * @return
     */
    @Override
    public List<ProductType> getTypeTree() {
        return productTypeMapper.getTypeTree();
    }
}
